/**
 * @author xxqin
 * @date 2018-04-04
 * @description:与原生app交互的方法定义 ，content都是josnString类型，eg:  测试vscode提交gitlab
 '{"status":200,"info":"获取信息成功","data":{"normal":543,"total":543,"alert":0,"fault":0,"sheilding":0}}'
 * */
var firstTime = 0;
let messageNotificationFull = null;
// 开启离线数据提交
var START_OFFLINE_COMMITDATA = false;

var native = (function (_self) {
  //====================  js触发native ========================


  window.addEventListener('online', function () {
    console.log('网络连接恢复！');
  })
  window.addEventListener('offline', function () {
    console.log('网络连接中断！');
  })

  /**
   * 图片url转base64
   * @param imgUrl
   */
  _self.converToBase64 = function (imgUrl) {
    function getBase64Image(imgUrl) {
      var canvas = document.createElement("canvas");
      canvas.width = imgUrl.width;
      canvas.height = imgUrl.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(imgUrl, 0, 0, imgUrl.width, imgUrl.height);
      var ext = imgUrl.src.substring(imgUrl.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    }

    var image = new Image();
    image.crossOrigin = "anonymous";
    image.src = imgUrl;
    image.onload = function () {
      var base64 = getBase64Image(image);
      console.log(base64);
    }
  }

  /**
   * 获取本地要提交的数据
   * @returns {any}
   */
  _self.getCommitWorkData = function () {
    let commitData = _self.getDataByKey("offlineData-work-commit-data");
    if (!commitData) {
      commitData = "[]";
    }
    return JSON.parse(commitData);
  }

  /**
   * 修改巡检离线数据
   */
  _self.updateInspectionData = function (data) {
    // 修改列表数据
    var param = {
      account: userInfor.accountName,
      status: 1, //执行中
    };
    let pointRes = JSON.parse(data.pointContentResultsSting)
    Dao.getInspectTaskInfoByStatus(param, function (dataList) {
      if (dataList && dataList.length > 0) {
        for (var i = 0; i < dataList.length; i++) {
          if (dataList[i].id == data.taskId) {

            dataList[i].examined += 1
            dataList[i].unIsOkNum += (pointRes.filter(m => {
              return m.result == 2
            }).length == 0 ? 0 : 1)

            // 修改列表数据
            let key1 = "offlineData-" + "app/examine/getTaskList" + JSON.stringify(param);
            var dataJSON1 = {
              status: 200,
              info: "操作成功",
              total: dataList.length,
              data: dataList
            }
            _self.saveDataByKey(key1, JSON.stringify(dataJSON1));

            // 修改任务详情
            let param3 = {
              taskId: data.taskId,
            }
            Dao.getInspectTaskDetail(param3, function (res) {
              let dataJSON3 = {
                status: 200,
                info: "操作成功",
                data: res
              }
              dataJSON3.data.pointList.forEach(n => {
                if (n.id == data.pointId) {
                  n.result = pointRes.filter(m => {
                    return m.result == 2
                  }).length == 0 ? 1 : 2
                }
              })
              dataJSON3.data.examined += 1
              let key3 = "offlineData-" + "app/examine/getExamineTaskDeatil" + JSON.stringify(param3);
              _self.saveDataByKey(key3, JSON.stringify(dataJSON3));
            }, true)

            // 修改任务点位巡检结果
            Dao.getExaminePointContentList({
              pointCode: data.pointCode
            }, function (res) {
              let param4 = {
                taskId: data.taskId,
                pointId: data.pointId
              }
              let dataJSON4 = {
                status: 200,
                info: "操作成功",
                data: res
              }
              dataJSON4.data.contentList.forEach(n => {
                let item = pointRes.filter(m => {
                  return m.contentId == n.id
                })[0]
                if (item) {
                  n.result = item.result
                  n.contentResult = item.contentResult
                }
              })
              let key4 = "offlineData-" + "app/examine/getTaskPointResult" + JSON.stringify(param4);
              _self.saveDataByKey(key4, JSON.stringify(dataJSON4));
            }, true)


            // 修改点位二维码扫描结果
            let param2 = {
              taskId: data.taskId,
              account: userInfor.accountName,
              pointCode: data.pointCode,
            };
            let key2 = "offlineData-" + "app/examine/getPointNowStatus" + JSON.stringify(param2);
            var dataJSON2 = {
              status: 200,
              info: "操作成功",
              total: 0,
              data: {
                info: "该点位已完成巡检",
                status: "205"
              }
            }
            _self.saveDataByKey(key2, JSON.stringify(dataJSON2));
          }
        }
      }
    });

    console.log("存储提交的巡检数据");
    let commitDataJSON = _self.getCommitWorkData();
    commitDataJSON.push({
      api: 'app/examine/commitPointResult',
      param: JSON.stringify(data),
      requestType: "post",
      userName: userInfor.accountName
    });
    _self.saveDataByKey("offlineData-work-commit-data", JSON.stringify(commitDataJSON));
  }
  let h5ResDownloadPrCallBack = null;
  /**
   * 下载离线数据
   */
  _self.loadOfflineWorkData = function (type, orgIds, callBack) {
    h5ResDownloadPrCallBack = callBack;

    if (/(Android)/i.test(navigator.userAgent)) {
      Dao.checkVersion({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        organizationId: 0,
        type: 5,
        isCustom: 0,
      }, function (data) {
        if (data) {
          try {
            nativeService.updateH5Data((ZHXF_IS_AIO ? location.origin : '') + data.url, data.softNumber);
          } catch (e) {

          }
        }
      });
    } else {
      h5ResDownloadPrCallBack(0, 1);
    }

    if (type.indexOf("1") > -1) {
      console.log("开始下载巡检数据");
      //执行中任务列表
      Dao.getInspectTaskInfoByStatus({
        account: userInfor.accountName,
        status: 1, //执行中
      }, function (data) {
        if (data.length == 0) {
          app.methods.showToastCenter('请先领取巡检任务', 2000)
        }
        _self.offlineInspectTaskApiCount = data.length
        _self.offlineInspectTaskAPiLoaded = 0
        for (var i = 0; i < data.length; i++) {
          var task = data[i]
          var taskId = task.id.toString()
          _self.getInspectTaskDetail(taskId)
        }

        let param = {
          account: userInfor.accountName,
        }
        let key = "offlineData-" + "app/examine/getTaskCount" + JSON.stringify(param);
        _self.saveDataByKey(key, JSON.stringify({
          status: 200,
          data: {
            noreceive: 0,
            execution: data.length
          }
        }));

      }, true);
    } else {
      _self.offlineInspectTaskApiCount = 0
      _self.offlineInspectTaskAPiLoaded = 0
    }

    if (type.indexOf("2") > -1) {
      console.log("开始下载维保数据");
      // 加载维保助手数据
      Dao.getTestTasksByAccount({
        account: userInfor.accountName,
      }, function (data, total) {
        if (data) {
          // 全部任务id
          let allId = [];
          for (let i = 0; i < data.length; i++) {
            let taskInfo = data[i];
            allId.push(taskInfo.id);
            // 获取状态
            Dao.getTestTaskStatus({
              userName: userInfor.accountName,
              account: userInfor.accountName,
              taskId: taskInfo.taskId.toString(), //任务id
              type: taskInfo.taskType, //type维保类型 1 维保巡查任务 2保养任务 3测试任务 4联动测试任务
            }, function (data2) {
              //获取楼栋数据
              Dao.getFbsMaintainTaskFinishResult({
                orgIds: taskInfo.orgId.toString(),
                taskId: taskInfo.taskId.toString(),
                allTaskFlg: 0, // 0-全部  1-剩余
              }, function (data3) {
                for (let j = 0; j < data3.length; j++) {
                  for (let k = 0; k < data3[j].fbsArr.length; k++) {
                    //获取楼层数据
                    Dao.getAssetsMaintainTaskDetail({
                      fbsId: data3[j].fbsArr[k].id.toString(),
                      taskId: taskInfo.taskId.toString(),
                      allTaskFlg: 0 // 0-全部 1-剩余
                    }, function (data4) {
                      if (data4) {
                        for (let l = 0; l < data4.length; l++) {
                          let objId = data4[l].businessType == 1 ? data4[l].assetsId : data4[l].fbsId;
                          // 获取作业详情页面基础数据
                          Dao.getTaskWorkInfo({
                            userName: userInfor.accountName,
                            deviceId: appKeyObj.deviceId,
                            taskId: taskInfo.taskId.toString(), //任务id
                            businessId: objId.toString(), //维保业务id
                            businessType: data4[l].businessType.toString(), //1单点2区域
                          }, function (data) {

                          }, true);

                          //根据二维码获取二维码类型
                          Dao.scanVCodeResult({
                            taskId: taskInfo.taskId.toString(),
                            qrCode: data4[l].visualCode,
                            maintainType: taskInfo.taskType //1 维保巡查任务 2保养任务 3测试任务 4联动测试任务
                          }, function (data) {

                          }, true);

                          Dao.getVisualCode({
                            orgCode: platformCode || app.data.defaultPlatCode,
                            visualCode: data4[l].visualCode,
                            orgIds: userInfor.organizationIds
                          }, function (data4, info, status) { }, true);

                          // 测试，联动测试
                          if (taskInfo.taskType == 3) {
                            Dao.getAlarmForTest({
                              account: userInfor.accountName,
                              userName: userInfor.accountName,
                              deviceId: appKeyObj.deviceId,
                              taskDetailId: data4[l].taskDetailId.toString(),
                              type: taskInfo.taskType.toString(),
                            }, function (data, total) {

                            }, true);
                          }
                        }
                      }
                    }, true);
                  }
                }
              }, true);
            });
            // 清单视图
            Dao.getMaintainTaskInfoDto({
              userName: userInfor.accountName,
              deviceId: appKeyObj.deviceId,
              taskId: taskInfo.taskId.toString(), //任务id
            }, function (data) {

            }, true);
            // 维保详情
            Dao.getMaintainTaskDetailInfoDtoForLD({
              userName: userInfor.accountName,
              deviceId: appKeyObj.deviceId,
              taskId: taskInfo.taskId.toString(), //任务id
            }, function (data) {

            }, true);

            // 测试，联动测试
            if (taskInfo.taskType == 4) {
              Dao.getAlarmForTest({
                account: userInfor.accountName,
                userName: userInfor.accountName,
                deviceId: appKeyObj.deviceId,
                taskDetailId: taskInfo.taskId.toString(),
                type: taskInfo.taskType.toString(),
              }, function (data, total) {

              }, true);

              Dao.getRelateAlarmCountByTaskId({
                userName: userInfor.accountName,
                deviceId: appKeyObj.deviceId,
                taskId: taskInfo.taskId.toString(),
              }, function (data, total) {

              }, true);
            }
          }

        }
      }, true);
    }
  }

  _self.getInspectTaskDetail = (taskId) => {
    // 获取任务详情
    Dao.getInspectTaskDetail({
      taskId
    }, function () {

      // 获取点位巡检内容
      Dao.getAppLineExaminePointContentList({
        taskId,
      }, function (res) {
        res && res.forEach(n => {
          // 点位巡检内容
          let url = 'app/examine/getExaminePointContentList'
          let key = "offlineData-" + url + JSON.stringify({
            pointCode: n.pointCode
          });
          _self.saveDataByKey(key, JSON.stringify({
            data: n,
            status: 200
          }))

          // 点位巡检结果
          let url2 = 'app/examine/getTaskPointResult'
          let key2 = "offlineData-" + url2 + JSON.stringify({
            taskId,
            pointId: n.id.toString(),
          });
          _self.saveDataByKey(key2, JSON.stringify({
            data: n,
            status: 200
          }))

          // 点位巡检状态
          let url3 = 'app/examine/getPointNowStatus'
          let key3 = "offlineData-" + url3 + JSON.stringify({
            taskId,
            account: userInfor.accountName,
            pointCode: n.pointCode
          });
          _self.saveDataByKey(key3, JSON.stringify({
            data: { "status": 200 },
            status: 200
          }))

        })
        _self.offlineInspectTaskAPiLoaded += 1
      }, true)

    }, true)
  }

  /**
   * 提交维保，修改数据
   * @param paramData 提交的数据
   * @param fbsId 建筑物数据
   */
  _self.updateMaintanceLocalData = function (paramData, fbsId, orgId, taskType) {
    console.log(paramData + "--" + fbsId + "--" + orgId)
    // 修改建筑物百分比 、 修改楼层数据
    var buildingParam = {
      orgIds: orgId.toString(),
      taskId: paramData.taskId.toString(),
      allTaskFlg: 0, // 0-全部  1-剩余
    };
    Dao.getFbsMaintainTaskFinishResult(buildingParam, function (data3) {
      for (let j = 0; j < data3.length; j++) {
        // 楼栋
        for (let k = 0; k < data3[j].fbsArr.length; k++) {
          // 楼层
          var floorParam = {
            fbsId: data3[j].fbsArr[k].id.toString(),
            taskId: paramData.taskId.toString(),
            allTaskFlg: 0 // 0-全部 1-剩余
          };
          // 楼层完成度加1
          // data3[j].fbsArr[k].finishCount++;
          //获取楼层下的点位数据
          Dao.getAssetsMaintainTaskDetail(floorParam, function (data4) {
            if (data4) {
              for (let l = 0; l < data4.length; l++) {
                // 楼层的点位
                if ((paramData.businessType == 1 && paramData.businessId == data4[l].assetsId) // 单点型
                  ||
                  (paramData.businessType == 2 && paramData.businessId == data4[l].fbsId)) { // 区域型
                  data4[l].finishFlg = 1;
                  // 楼栋完成度加1
                  data3[j].finishCount++;
                  data3[j].fbsArr[k].finishCount += data4[l].assetsCount
                  console.log(data3[j].fbsArr[k].finishCount)
                  var vcodrParam = {
                    taskId: paramData.taskId.toString(),
                    qrCode: data4[l].visualCode,
                    maintainType: taskType //1 维保巡查任务 2保养任务 3测试任务 4联动测试任务
                  };
                  //根据二维码获取二维码类型
                  Dao.scanVCodeResult(vcodrParam, function (data) {

                    let keyVCode = "offlineData-" + "app/maintenance/scanVCodeResult" + JSON.stringify(vcodrParam);
                    let dataJsonVCode = {
                      status: 200010,
                      info: "当前已维保完成！",
                      total: 0,
                      data: null
                    }
                    _self.saveDataByKey(keyVCode, JSON.stringify(dataJsonVCode));
                  }, true);
                  break;
                }
              }

              let keyFloorPoint = "offlineData-" + "app/maintenance/getAssetsMaintainTaskDetail" + JSON.stringify(floorParam);
              let dataJsonFloorPoint = {
                status: 200,
                info: "操作成功",
                total: data4.length,
                data: data4
              }
              _self.saveDataByKey(keyFloorPoint, JSON.stringify(dataJsonFloorPoint));
            }
          }, true); // 楼层信息
        }
      }
      // 修改列表数据
      let keyBuilding = "offlineData-" + "app/maintenance/getFbsMaintainTaskFinishResult" +
        JSON.stringify(buildingParam);
      var dataJSONBuilding = {
        status: 200,
        info: "操作成功",
        total: data3.length,
        data: data3
      }
      _self.saveDataByKey(keyBuilding, JSON.stringify(dataJSONBuilding));
    }, true); // 楼栋信息

    // 修改清单界面数据
    var mInfoParam = {
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
      taskId: paramData.taskId.toString(), //任务id
    };
    Dao.getMaintainTaskInfoDto(mInfoParam, function (dataInfo) {
      if (dataInfo) {
        console.log(dataInfo)
        dataInfo.finishCount++;
        var picBeforeUrlsParam = paramData.picBeforeUrls;
        var picAfterUrlsParam = paramData.picAfterUrls;
        var time = _self.getNowFormatDate();
        dataInfo.beforeWorkPicList[time] = picBeforeUrlsParam;
        dataInfo.afterWorkPicList[time] = picAfterUrlsParam;
        // 修改列表数据
        let key1 = "offlineData-" + "app/maintenance/getMaintainTaskInfoDto" + JSON.stringify(mInfoParam);
        var dataJSON1 = {
          status: 200,
          info: "操作成功",
          total: 0,
          data: dataInfo
        }
        _self.saveDataByKey(key1, JSON.stringify(dataJSON1));
      }
    }, true);

    // 联动测试修改维保助手页面接口数据
    Dao.getTestTasksByAccount({
      account: userInfor.accountName,
    },
      function (dataList, total) {
        if (dataList) {
          for (let i = 0; i < dataList.length; i++) {
            let taskInfo = dataList[i];
            if (taskInfo.taskId == paramData.taskId && taskInfo.taskType == 4) {
              taskInfo.complete = taskInfo.total;
              // 修改列表数据
              let key1 = "offlineData-" + "app/maintenance/getTestTasksByAccount" +
                JSON.stringify({
                  account: userInfor.accountName
                });
              var dataJSON1 = {
                status: 200,
                info: "操作成功",
                total: dataList.length,
                data: dataList
              }
              _self.saveDataByKey(key1, JSON.stringify(dataJSON1));
              break;
            }
          }
        }
      }, true);
  }

  //获取当前时间，格式YYYY-MM-DD
  _self.getNowFormatDate = function () {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  }

  /**
   * 维保数据
   * @param data
   */
  _self.postTaskWorkInfo = function (paramData) {
    console.log("存储提交的维保数据");
    let commitDataJSON = _self.getCommitWorkData();
    commitDataJSON.push({
      api: 'app/maintenance/addTaskDetailOfTask',
      param: JSON.stringify(paramData),
      requestType: "post",
      userName: userInfor.accountName
    });
    native.saveDataByKey("offlineData-work-commit-data", JSON.stringify(commitDataJSON));
  }

  /**
   * 删除离线缓存的数据
   * @param delId
   */
  _self.deleteGetTestTasksByAccountListData = function (delId) {
    var param = {
      account: userInfor.accountName,
    }
    // 加载维保助手数据
    Dao.getTestTasksByAccount(param,
      function (dataList, total) {
        if (dataList) {
          for (let i = 0; i < dataList.length; i++) {
            let taskInfo = dataList[i];
            if (taskInfo.id == delId) {
              dataList.splice(i, 1);
              // 修改列表数据
              let key1 = "offlineData-" + "app/maintenance/getTestTasksByAccount" + JSON.stringify(param);
              var dataJSON1 = {
                status: 200,
                info: "操作成功",
                total: dataList.length,
                data: dataList
              }
              _self.saveDataByKey(key1, JSON.stringify(dataJSON1));
              break;
            }
          }
        }
      }, true);

  }


  /**
   * 结束任务
   * @param data
   */
  _self.endTestTask = function (data) {
    _self.deleteGetTestTasksByAccountListData(data.id);

    console.log("存储结束任务数据");
    let commitDataJSON = _self.getCommitWorkData();
    commitDataJSON.push({
      api: 'app/maintenance/endTestTask',
      param: JSON.stringify(data),
      requestType: "post",
      userName: userInfor.accountName
    });
    native.saveDataByKey("offlineData-work-commit-data", JSON.stringify(commitDataJSON));
  }

  /**
   * 结束所有任务
   * @param data
   */
  _self.endTasksByIds = function (data) {
    // 设置列表数据为空
    var param = {
      account: userInfor.accountName,
    }
    // 修改列表数据
    let key1 = "offlineData-" + "app/maintenance/getTestTasksByAccount" + JSON.stringify(param);
    var dataJSON1 = {
      status: 200,
      info: "操作成功",
      total: 0,
      data: null
    }
    _self.saveDataByKey(key1, JSON.stringify(dataJSON1));

    console.log("存储结束所有任务数据");
    let commitDataJSON = _self.getCommitWorkData();
    commitDataJSON.push({
      api: 'app/maintenance/endTasksByIds',
      param: JSON.stringify(data),
      requestType: "post",
      userName: userInfor.accountName
    });
    native.saveDataByKey("offlineData-work-commit-data", JSON.stringify(commitDataJSON));
  }

  /**
   * 离线作业数据下载进度
   * @param status 0表示正常下载中，1表示下载失败
   * @param info 描述信息
   * @param progress 下载进度
   */
  _self.h5ResDownloadProgress = function (status, info, progress) {
    console.log("\nsetOfflineProgress:" + status + "," + info + "," + progress);
    if (h5ResDownloadPrCallBack) {
      h5ResDownloadPrCallBack(status, progress);
    }
  }

  /**
   * explain:存储用户信息
   * @returns param { }
   */
  _self.setUserInfor = function (data) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.setUserInfor(JSON.stringify(data));
      } catch (e) {
        // app.methods.showToastBottom('保存用户信息出错');
      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.setUserInfor.postMessage(JSON.stringify(data));
      } catch (e) {
        //app.methods.showToastBottom('保存用户信息出错');
      }
    } else {
      localStorage.setItem("LOCAL_USERINFO", JSON.stringify(data));
    }

    _self.saveDataByKey('LOCAL_USERINFO', JSON.stringify(userInfor))
    _self.saveDataByKey('QINIUPATH', FILEDOWNLOADPATH)
    _self.saveDataByKey('uploadOnNginx', uploadOnNginx ? 'true' : 'false')
    _self.saveDataByKey('platformCode', platformCode)
    _self.saveDataByKey('appKeyObj', JSON.stringify(appKeyObj))
    _self.saveDataByKey('contextPath', contextPath)
  }
  /**
   * explain:获取用户信息
   * @returns param { }
   */
  _self.getUserInfor = function () {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        var userInfo = nativeService.getUserInfor();
        if (userInfo) {
          userLoggedIn = true;
        } else {
          userLoggedIn = false;
        }
        return JSON.parse(userInfo);
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        //js调oc
        window.webkit.messageHandlers.jsgetUserInfor.postMessage('');
      } catch (e) {

      }
    } else {
      return JSON.parse(localStorage.getItem("LOCAL_USERINFO"));
    }

  }

  /**
   * explain:打开原生程序
   * @returns param { }
   */
  /*
     code 1 打开资产列表
          2 维护到期
          3 质保到期
          4 资产详情
     date orgID(code：1，2，3)
          资产ID（code：4）
  */
  _self.openFunction = function (code, date) {
    if (code == 1) { //资产列表
      app.router.navigate('/assetsList/' + date + '/0/');
    } else if (code == 4) { //资产详情
      app.router.navigate('/assetsDetail/0/' + date + '/');
    } else {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.openFunction(code, date);
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          var zcdic = {
            'code': code,
            'date': date
          };
          window.webkit.messageHandlers.jsgetZCview.postMessage(zcdic);
        } catch (e) {

        }
      }
    }
  }
  /**
   * explain:获取原生appKey 、secretKey、deviceId、dpi,systemContext
   * @returns param { }
   */
  _self.getAppKey = function () {
    let platformCode = GetQueryString('loginId') || PLATCOEDEFAULT;
    //如果没有，给一个默认值，用于调试或者浏览器里访问
    let webAppInfo = WEBCONFIG[platformCode] || WEBCONFIG[CONFIGKEY]
    //本地调试赋值一个设备信息
    if (isDebug) {
      return _self.dealJson(JSON.stringify(webAppInfo));
    }
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        return JSON.parse(nativeService.getAppKey());
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.jsgetAppKey.postMessage('');
      } catch (e) {

      }
    } else {
      // 根据不同的项目环境修改
      return _self.dealJson(JSON.stringify(webAppInfo));
    }
  }

  /**
   * 获取版本号
   */
  _self.getVersion = function () {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        return nativeService.getVersion();
      } catch (e) {
        return 0;
      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.IOSVersion.postMessage('');
      } catch (e) {
        return 0;
      }
    } else {
      return 0;
    }
  }

  /**
   * 获取js版本号
   */
  _self.getjsVersion = function () {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端

    if (isAndroid) {
      try {
        return nativeService.getjsVersion();
      } catch (e) {
        return 0;
      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.H5Version.postMessage('');
      } catch (e) {
        return 0;
      }
    } else {
      return 0;
    }
  }

  /**
   * explain: 保存js版本到原生
   * @returns param {}
   */
  _self.savejsVersion = function (value) {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.savejsVersion(value);
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          var bykey = {
            'key': 'H5Version',
            'value': value
          };
          window.webkit.messageHandlers.savaH5Version.postMessage(bykey);
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }



  /**
   * 获取版本名称
   */
  _self.getVersionName = function () {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        return nativeService.getVersionName();
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.jsgetVersionName.postMessage('');
      } catch (e) {

      }
    } else {
      return "";
    }
  }

  /**
   * explain:发起导航
   * @returns param { long lng,long lat}
   */
  _self.openNavigation = function (lng, lat) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.openNavigation(lng, lat);
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        var bykey = {
          'lng': lng,
          'lat': lat
        };
        window.webkit.messageHandlers.openNavigation.postMessage(bykey);
      } catch (e) {

      }
    } else {

    }
  }


  /**
   * explain:获取定位
   * @returns param { long lng,long lat}
   */
  _self.requestLocation = function (inspectId) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.requestLocation();
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.jslocationResult.postMessage(inspectId);
      } catch (e) {

      }
    }
  }

  /**
   * explain:打开相机；
   * @returns param { }
   */
  _self.openCamera = function () {
    try {
      nativeService.openCamera();
    } catch (e) {

    }
  }

  /**
   * explain:打开相册
   * @returns param { }
   */
  _self.openPhotos = function () {
    try {
      nativeService.openPhotos();
    } catch (e) {

    }
  }
  /**
   * explain:下载
   * @returns param { }
   */
  _self.downloadByBrowser = function (url) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.downloadByBrowser(url);
      } catch (e) {

      }
    } else if (isIOS) {
      try {

        window.webkit.messageHandlers.gotoAppstore.postMessage(url);
      } catch (e) {

      }
    }
  }

  /**
   * explain:清除缓存
   * @returns param { }
   */
  _self.clear_cache = function () {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    try {
      if (isAndroid) {
        nativeService.cleanCache();
      } else if (isIOS) {
        window.webkit.messageHandlers.clear_cache.postMessage('');
      }
    } catch (e) {

    }
  }
  /**
   * explain:引入新的js
   * @returns param { }
   */
  _self.addJsFile = function () {
    var jsFlies = ["js/common/common.js", "js/common/native.js", "js/routes.js", "js/login.js", "js/app.js", "js/index.js", "js/common/Dao.js"];
    for (var i = 0; i < jsFlies.length; i++) {
      addCssByLink(jsFlies[i]);
    }
  }

  var addCssByLink = (function (url) {
    var doc = document;
    var link = doc.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);

    var heads = doc.getElementsByTagName("head");
    if (heads.length)
      heads[0].appendChild(link);
    else
      doc.documentElement.appendChild(link);
  });

  /**
   * explain: 打开视频
   * identity ：视频认证信息
   * videoInfo ：视频信息
   * @returns param {Object identity,Object videoInfo }
   */
  _self.openVideo = function (identity, videoInfo) {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.openVideo(identity, videoInfo);
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        var video_msg = {
          'identity': identity,
          'videoInfo': videoInfo
        };
        window.webkit.messageHandlers.openVideo.postMessage(video_msg);
      } catch (e) {

      }
    }
  }

  /**
   * explain: 分享
   * way:分享方式，QQ、微信、朋友圈、微博
   * type：分享的数据类型，例如：url，text
   * content:分享的内容
   * @returns param {int way,int type,String content}
   */
  _self.shareTo = function (way, type, content) {
    try {
      nativeService.shareTo(way, type, content);
    } catch (e) {

    }
  }

  /**
   * explain: 微信登录
   * @returns param {}
   */
  _self.loginByWx = function () {
    return _self.dealJson('{"status":1001,"info":"未绑定用户","data":{}}', 1);
    try {
      nativeService.loginByWx();
    } catch (e) {

    }
  }
  /**
   * explain: 二维码扫描
   * @returns param {}
   */
  _self.scanQrCode = function () {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.scanQrCode();
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.jsscanQrCode.postMessage('');
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }
  /**
   * explain: 原生调用nfc
   * @returns param {}
   */
  _self.startNfcDialog = function () {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      if (isAndroid) {
        try {
          if (app.view.get("#home")) {
            var isSupportNFC = native.startNFC();
            var nfc = isSupportNFC.split(",");
            if (nfc[0] == 0) {
              app.dialog.create({
                title: '提示',
                text: '当前设备暂不支持NFC扫描功能',
                buttons: [{
                  text: '确定',
                  click: function () { }
                }],
                verticalButtons: true,
              }).open();
            } else {
              this.nfcDialog = app.dialog.create({
                title: '提示',
                text: nfc[1] == 0 ? '请先在设置中启用NFC功能' : '请将设备靠近巡检点位标签',
                buttons: [{
                  text: nfc[1] == 0 ? '确定' : '取消',
                  onClick: function () {
                    if (nfc[1] == 0) {

                    } else {
                      // 取消扫面二维码，关闭NFC扫描资源
                      native.stopNFC();
                    }
                  }
                }],
                verticalButtons: true,
              });
              this.nfcDialog.open();
            }
          } else {
            app.view.current.el.f7View.router.currentPageEl.f7Component.nFCrecognition();
          }

        } catch (e) {

        }
      }
    } catch (e) {

    }
  }

  /**
   * explain: 保存数据到原生
   * @returns param {}
   */
  _self.saveDataByKey = function (key, value) {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.saveDataByKey(key, value);
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          var bykey = {
            'key': key,
            'value': value
          };
          window.webkit.messageHandlers.saveDataforIOS.postMessage(bykey);
        } catch (e) {

        }
      } else {
        localStorage.setItem(key, value);
      }
    } catch (e) {

    }
  }


  /**
   * explain: 获取原生数据
   * @returns param {}
   */
  _self.getDataByKey = function (key) {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          var data = nativeService.getDataByKey(key);
          // console.log("\n\nkey："+key+"，\n获取到Android数据：\n"+data);
          return data;
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.jssaveDataforIOS.postMessage(key);
        } catch (e) {

        }
      } else {
        var data = localStorage.getItem(key);
        // console.log("\n\nkey："+key+"，\n获取到localStorage数据：\n"+data);
        return data;
      }
    } catch (e) {

    }
  }

  /**
   * explain: 启动科大讯飞语音输入
   * @returns param {}
   */
  _self.startVoice = function (componentId, flag) {
    try {
      // app.methods.showToastIcon();
      voiceDialog("请开始说话", staticPath + "img/hidden/check-multi-task.png", function () {
        layer.closeAll();
        native.stoplVoice();
      });

      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.startVoice(componentId, flag);
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          var bykey = {
            'componentId': componentId,
            'flag': flag
          };
          window.webkit.messageHandlers.startVoice.postMessage(bykey);
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }

  /**
   * explain: 启动科大讯飞语音合成
   * @returns param {}
   */
  _self.startTetToTtsVoice = function (context) {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          console.log(nativeService.startTetToTtsVoice(context))
          return nativeService.startTetToTtsVoice(context);
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.startTetToTtsVoice.postMessage(context);
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }

  function MailView(url, shareTitle, shareContent) {
    let htmlMail = `
        <div class="popup dector-popup">
            <div>分享到邮箱</div>
            <div style="margin-top:20px;">收件人</div>
            <div style="width:100%; margin:0 auto; background:#EBEBEB; position:relative;">
		        <div class="ln"><input style="width:100%; height:28px; margin:10px 0; line-height:28px;" type="text" maxlength="128" name="loginName" id="loginName" placeholder="请填写邮箱" /></div>
		        <ul class="on_changes" style="width: 100%; position: absolute; top: 31px; list-style: none; background: rgb(255, 255, 255); border: 1px solid rgb(0, 0, 0); height: 150px; overflow: scroll; display: none;">
                    <li style="margin:8px;padding:4px;" email="">请选择邮箱类型</li>
                    <li style="margin:8px;padding:4px;" email=""></li>
                    <li style="margin:8px;padding:4px;" email="@sina.com"></li>
                    <li style="margin:8px;padding:4px;" email="@163.com"></li>
                    <li style="margin:8px;padding:4px;" email="@qq.com"></li>
                    <li style="margin:8px;padding:4px;" email="@hotmail.com"></li>
                    <li style="margin:8px;padding:4px;" email="@126.com"></li>
                    <li style="margin:8px;padding:4px;" email="@gmail.com"></li>
                    <li style="margin:8px;padding:4px;" email="@yahoo.com"></li>
		        </ul>
            </div>
            <div style="margin-top:20px;">邮件标题</div>
            <div style="margin-top:20px;margin-right:20px;color: #999;">` + shareTitle + `报表</div>
            <div style="margin-top:20px;">邮件内容</div>
            <div style="margin-top: 20px;color: #999;height: auto;word-break: break-all;overflow: hidden;">你好，【` + shareTitle + `报表】已经生成，请点击` + url + `   查看</div>
            <div style="display:flex;width=100%;height:50px;">
                <div style="background-color: #ff0000;font-size: 17px;color: #ffffff;width: 40%; height: 40px; justify-content: center; align-items: center; display: flex;bottom: 10px;position: absolute; left: 10px" id="canleclick">取消</div>
                <div style="background-color: #378bf6;font-size: 17px;color: #ffffff;width: 40%; height: 40px; justify-content: center; align-items: center; display: flex;bottom: 10px;position: absolute; right: 10px;" id="niuclick">发送</div>
            </div>
        </div>
        `;
    //加载邮箱弹框
    creatNewPopup(htmlMail, function () { });
    //取消按钮
    jQuery("#canleclick").click(function () {
      colsePopup();
    });
    //关闭邮箱弹框
    jQuery("#niuclick").click(function () {
      var mailNumber = $('#loginName').val();
      if (mailNumber.length != 0) {
        colsePopup();
        Dao.shareReportMail({
          userName: userInfor.accountName,
          deviceId: appKeyObj.deviceId,
          title: shareTitle + "报表",
          mails: mailNumber,
          content: "你好，【" + shareTitle + "报表】已经生成，请点击" + url + "  查看"
        }, function (data) {
          app.methods.showToastCenter("邮件发送成功");
        });
      } else {
        app.methods.showToastCenter("邮箱地址不能为空");
        return;
      }
    });
    //统一关闭弹框
    function colsePopup() {
      app.popup.close();
    }
    //邮件输入框关联后缀
    jQuery(function () {

      jQuery("#loginName").changeTips({
        divTip: ".on_changes"
      });
    })
  }
  /**
   * explain: 分享
   * @returns param {}
   */
  _self.shareReport = function (url, shareTitle, shareContent, isEmail) {
    common.loading(0);
    shareBbView(isEmail, function (shareTypeString) {
      // shareTypeString 返回值是下方五个字符串
      //WxFriends       微信
      //WxFriendsMoment 朋友圈
      //QQFriends       QQ
      //Qzone           QQ空间
      //Mail            邮件  
      //systemShare     系统分享
      if (shareTypeString == "Mail") {
        MailView(url, shareTitle, shareContent);
      } else if (shareTypeString == "systemShare") {
        // TODO 原生分享
        console.log('原生分享')
        if (shareTitle) {
          url = url + "&shareTitle=" + shareTitle;
        }
        if (shareContent) {
          url = url + "&shareContent=" + shareContent;
        }
        if (shareTypeString) {
          url = url + "&shareTypeString=" + shareTypeString;
        }
        try {
          window.webkit.messageHandlers.shareReport.postMessage(url);
        } catch (e) {

        }
      } else {
        try {
          var u = navigator.userAgent;
          var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
          var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
          if (shareTitle) {
            url = url + "&shareTitle=" + shareTitle;
          }
          if (shareContent) {
            url = url + "&shareContent=" + shareContent;
          }
          if (shareTypeString) {
            url = url + "&shareTypeString=" + shareTypeString;
          }
          if (isAndroid) {
            try {
              return nativeService.shareReport(url);
            } catch (e) {

            }
          } else if (isIOS) {
            try {
              window.webkit.messageHandlers.shareReport.postMessage(url);
            } catch (e) {

            }
          }
        } catch (e) {

        }
      }
    });
  }

  /**
   * explain: 停止科大讯飞语音识别
   * @returns param {}
   */
  _self.stoplVoice = function () {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          return nativeService.stoplVoice();
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.stoplVoice.postMessage('');
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }

  /**
   * explain:语音输入
   * code:结果码
   * content：内容  str
   * @returns
   */
  _self.voiceCollection = function (voiceStr, componentId) {
    layer.closeAll();
    app.view.current.el.f7View.router.currentPageEl.f7Component.voiceCollectionData(voiceStr, componentId);
  }

  /**
   * explain: 通知原生上传语音文件
   * @returns param {}
   */
  _self.saveTheVoiceFile = function (orgId) {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.saveTheVoiceFile(orgId);
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.saveTheVoiceFile.postMessage(orgId);
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }

  /**
   * explain:原生回调给js语音文件url
   * code:结果码
   * content：内容  str
   * @returns
   */
  _self.callbackVoiceFile = function (voiceUrl, wavLength) {
    app.view.current.el.f7View.router.currentPageEl.f7Component.callbackVoiceFile(voiceUrl, wavLength);
  }

  /**
   * explain: 通知原生关闭语音播放文件
   * @returns param {}
   */
  _self.turnOffVoicePlay = function () {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.turnOffVoicePlay();
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.turnOffVoicePlay.postMessage('');
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }

  /**
   * explain: 通知原生暂停、继续播放
   * @returns param {}
   */
  _self.pauseSpeakingAtBoundary = function () {
    try {
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isAndroid) {
        try {
          nativeService.pauseSpeakingAtBoundary();
        } catch (e) {

        }
      } else if (isIOS) {
        try {
          window.webkit.messageHandlers.pauseSpeakingAtBoundary.postMessage('');
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }
  //
  /**
   * explain:
   * @returns param {}
   */
  _self.keyUpDown = function () {
    try {
      var u = navigator.userAgent;
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isIOS) {
        try {
          window.webkit.messageHandlers.keyUpDown.postMessage('');
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }
  /**
   * explain:
   * @returns param {}
   */
  _self.openKeyUpDown = function () {
    try {
      var u = navigator.userAgent;
      var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
      if (isIOS) {
        try {
          window.webkit.messageHandlers.openKeyUpDown.postMessage('');
        } catch (e) {

        }
      }
    } catch (e) {

    }
  }
  /**
   * explain:开始扫描NFC
   * @returns string
   * 0, 0 不支持
   * 1,0 支持，但未打开NFC功能
   * 1,1 支持，并且已经打开NFC功能
   */
  _self.startNFC = function () {
    try {
      return nativeService.startNFC();
    } catch (e) {
      return '0,0';
    }
  }

  /**
   * explain:停止扫描NFC
   * @returns string
   */
  _self.stopNFC = function () {
    try {
      nativeService.stopNFC();
    } catch (e) {

    }
  }

  //=================== ios native触发js  =====================
  /*
     data ios原生调用js方法
     js拿oc登录信息
 */
  _self.jsgetUserInfor = function (data) {
    try {
      // 先注释，影响IOS APP自动登录,但是会影响第一次打开APP检测是被都挤线下
      userInfor = JSON.parse(data);
      common.loading(1);
      // if (userInfor) {
      //     userLoggedIn = true;
      // } else {
      //     userLoggedIn = false;
      // }
      setTimeout(() => {
        common.loading(0);
        if (userLoggedIn == false) {
          // userLoggedIn = true;
          // login.signIn();
        }
      }, 1000);
      // return JSON.parse(data);
    } catch (e) {

    }
  }

  /*
         data ios原生调用js方法
         js拿oc的记住密码和设备id信息
     */
  _self.jsgetDataByKey = function (data) {

    try {
      var dic = userInfor
      if (dic.accountName) {
        // jQuery("#login-form input[name='accout']")[0].value = dic.accountName;
      }
      if (dic.password) {
        // jQuery("#login-form input[name='password']")[0].value = 'wwhl123456'//'111111';
      }
      if (dic.loginStatus != undefined) {
        loginStatus = dic.loginStatus;
      }
      // var user_str = userInfor.accountName;
      // if (dic[user_str] != undefined) {
      //     jQuery.each(dic, function (key, val) {
      //         if (key != undefined) {
      //             if (PollingCode == '') {
      //                 PollingCode = val;
      //             } else {
      //                 PollingCode = PollingCode + ',' + val;
      //             }
      //         }
      //     })
      // }

    } catch (e) {

    }
  }
  /*
         data ios原生调用js方法
         js拿oc的Appkey和设备id信息
     */
  _self.jsgetAppKey = function (data) {
    try {
      appKeyObj = JSON.parse(data);
      return JSON.parse(data);
    } catch (e) {

    }
  }
  /*
        data ios原生调用js方法
        js拿oc的原生版本号和设备id信息
    */
  _self.jsgetVersionName = function (data) {
    try {
      $(".versions_class").html('v' + data);
    } catch (e) {

    }
  }
  /*
      data ios原生调用js方法
      js拿oc的原生版本号
  */
  _self.IOSVersion = function (data) {
    try {
      IOSVersion = data;
    } catch (e) {

    }
  }

  _self.getIOSVersion = function () {
    try {
      return IOSVersion;
    } catch (e) {

    }
  }

  /*
       data ios原生调用js方法
       js拿h5的版本号
   */
  _self.H5Version = function (data) {
    try {
      CONFIGBOX[CONFIGKEY].version = parseInt(data);
    } catch (e) {

    }
  }


  //====================  native触发js ========================
  /**
   * explain:上传图片
   * path：本地路径，progress：上传进度
   * @returns param { String path,int progress }
   */
  _self.uploadProgress = function (path, progress) {

  }

  /**
   * explain:上传完成
   * path：本地路径，url：上传后的url地址
   * @returns param { String path,String url}
   */
  _self.uploadComplete = function (path, url) {

  }


  /**
   * explain:收到语音转换文字
   * msgJson:消息string
   * @returns param
   */
  _self.voiceGetText = function (content) {
    app.methods.showToastCenter(content);
  }

  //当前页是message頁面时刷新
  _self.receiveMessageTab = function () {
    if ((app.data.currentActiveTab == "message")) {
      app.view.get("#message").router.currentPageEl.f7Component.receivePushMsg();
    }
    getUnReadMsgCount();
  }

  /*-----推送----------------------------------------------------------------------------*/

  /**
   * explain:Android收到推送，弹框提醒(点击状态栏打开app后解析数据)不跳转；
   * msgJson:消息json
   * @returns param { Json msgJson}
   */
  _self.receivePushMsg = function (oContent, oContext) {
    if (oContent && oContext) {
      IsNewMsg = true;
      _self.receiveMessageTab();
      push.getPush(oContent, oContext);
    }
  }

  /**
   * ios接收推送消息时
   * @param {*} content
   */
  _self.receivePushMsgForIos = function (oContent, oContext) {
    if (oContent && oContext) {
      IsNewMsg = true;
      _self.receiveMessageTab();
      push.getPush(oContent, oContext);
    }
  }

  /**
   * explain: 点击推送跳转到指定页面
   * @returns param {}
   * Android:点击通知栏触发
   * Ios:点击通知栏触发
   */
  _self.jumpToSpecifiedPage = function (oContent, oContext) {
    push.getPush(oContent, oContext, true);
  }

  /*-----推送----------------------------------------------------------------------------*/


  /**
   * explain:分享结果
   * code:结果码
   * msg：分享结果信息
   * @returns param { int code,String msg}
   */
  _self.shareResult = function (content) {

  }

  /**
   * explain:二维码扫描结果
   * code:结果码
   * content：扫描内容
   * @returns param {int code,String content}
   */
  _self.scanResult = function (content) {
    if (!content || "" === content.trim()) {
      app.methods.showToastCenter("二维码/条码扫描失败，请重试。");
      return;
    }
    content = content.replace('\t', '')
    content = content.replace('UTF-8', '')
    // console.log('查看content隐藏字符:',JSON.stringify(content))
    var pageEl = app.view.current.el.f7View.router.currentPageEl.f7Component;
    if ((pageEl && pageEl.pageName == "allBuild") || (pageEl && pageEl.pageName == "remainBuild")) {
      pageEl.scanningreciviceLocation(content);
    } else if ((pageEl && pageEl.pageName == "maintainDetail") || (pageEl && pageEl.pageName == "maintainInspectDetail")) {
      pageEl.scanningreciviceLocation(content);
    } else if (pageEl && pageEl.pageName == "signIn") {
      pageEl.scanningreciviceLocation(content);
    } else if (pageEl && pageEl.$route.name == "addDevice") {
      pageEl.scanningreciviceLocation(content);
    } else if (pageEl && pageEl.$route.name == "checkApply") {
      pageEl.scanningreciviceLocation(content);
    } else {
      //获取二维码信息
      _self.getQrcodeMes(content);
    }
  }

  /*获取二维码信息*/
  _self.getQrcodeMes = function (qRcode) {
    // 花桥bugfix
    qRcode = qRcode.replace('\t', '').replace('UTF-8', '')
    let pageEl = app.view.current.el.f7View.router.currentPageEl;
    if (pageEl.f7Component && pageEl.f7Component.pageName == 'changeShifts' || qRcode.indexOf('?') > -1) { //交接班
      let timeStartStamp = qRcode.split('?')[1]
      let timeNowStamp = (new Date()).getTime()
      if (timeNowStamp - timeStartStamp > 60000) {
        app.methods.showToastCenter('二维码/条码已经失效')
        return;
      } else {
        qRcode = qRcode.split('?')[0]
      }
    } else {
      qRcode = qRcode
    }
    Dao.getVisualCode({
      orgCode: platformCode || app.data.defaultPlatCode,
      visualCode: qRcode,
      orgIds: userInfor.organizationIds
    }, function (data, info, status) {
      if (data) {
        //在首页扫码
        if (!pageEl.f7Component) {
          //1资产
          if (data.type == 1) {
            app.router.navigate("/assetsDetail/" + data.objId + "/" + data.visualCode + '/');
          }
          //2巡检点位
          else if (data.type == 2) { //巡检点位/waitApply/:taskId/:orgId/
            _self.cancelCheckQrcode(data);
            //app.router.navigate("/waitApply/"+data.objId+"/"+data.visualCode+'/');
          } else if (data.type == 3) { //建筑物/assetsListForSingle/:orgId/:fbsId/
            // app.router.navigate("/assetsListForSingle/"+data.orgId+"/"+data.objId+"/"+data.fbsName+'/');
            app.methods.showToastCenter('当前建筑：' + data.fbsName)
          } else if (data.type == 4) { //交接班
            QrStatus = true
            app.popup.close();
            app.router.navigate("/changeShiftsDetails/" + data.objId + "/" + 3 + '/');
          }
        } else {
          //巡检
          if (pageEl.f7Component.pageName == "checkApply") {
            _self.cancelCheckQrcode(data);
          }
          //保养/维保巡查/单点测试
          else if (pageEl.f7Component.pageName == "maintainDetail" ||
            pageEl.f7Component.pageName == "maintainInspectDetail") {
            _self.cancelMainteceQrcodResult(data, pageEl.f7Component.pageName);
          }
          //在资产页面
          else if (pageEl.f7Component.pageName == "assetsList" ||
            pageEl.f7Component.pageName == "assetsListForSingle" ||
            pageEl.f7Component.pageName == "assetsListForMore") {
            //1：资产 2：巡检点位,3建筑物
            //资产页面 type 是3的情况暂时不管
            if (data.type == 1) {
              app.router.navigate("/assetsDetail/" + data.objId + "/" + data.visualCode + '/');
            } else if (data.type == 3) {
              app.methods.showToastCenter('当前建筑：' + data.fbsName)
            }
          } else if (pageEl.f7Component.pageName == "changeShifts") {
            if (data.type == 4) { //交接班
              QrStatus = true
              app.router.navigate("/changeShiftsDetails/" + data.objId + "/" + 3 + '/');
            }
          }
        }
      } else {
        if (info) {
          custom.tipSimple(3, info);
        }

      }
    });
  }

  /*二维码扫描后的相关处理*/
  _self.cancelMainteceQrcodResult = function (data, pageName) {
    let maintainType = null;
    if (pageName == "maintainInspectDetail") {
      maintainType = 1;
    } else if (pageName == "maintainDetail") {
      maintainType = 2;
    }
    Dao.scanVCodeResult({
      taskId: data.objId,
      qrCode: data.visualCode,
      maintainType: maintainType //1 维保巡查任务 2保养任务 3测试任务 4联动测试任务
    }, function (data) {
      if (data.status == 200) {
        let id = data.data.businessId;
        let type = data.data.businessType;
        //未开始的任务不能跳转
        if (data.data.testTaskStatus != 0) {
          //保养详情页面
          if (pageName == "maintainDetail") {
            app.router.navigate("/maintainTask/" + self.taskId + "/" + id + "/" + type + "/");
          }
          //维保巡查详情页面
          else if (pageName == "maintainInspectDetail") {
            app.router.navigate("/maintainInspectTask/" + self.taskId + "/" + id + "/" + type + "/");
          }
        } else {
          app.methods.showToastCenter("请先开始任务");
        }
      } else {
        custom.tipSimple(3, data.info);
      }
    });
  }

  // 处理巡检二维码
  _self.cancelCheckQrcode = function (re) {
    let taskId = ''
    let pointCode = re.visualCode
    Dao.getTodayPonitStatusNew({
      pointCode,
      account: userInfor.accountName,
    }, function (data) {
      if (data.status == 200) {
        taskId = data.info
        app.router.navigate(`/checkApply/InspectPoint/${taskId}/0/${pointCode}/`);
      } else {
        custom.tipSimple(3, data.info);
      }
    });
  }

  /**
   * explain:网络变动 巡检离线上传
   *
   */
  var codeArray = []; //离线上传巡检任务
  var nativeData = [];
  var progress = 0;
  var dialog = null;

  _self.connectionChange = function (data) {
    //巡检点位离线上传
    var self = this;
    var codeData = '';

    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        codeData = native.getDataByKey(userInfor.accountName)
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        var dic = JSON.parse(data)
        var user_str = userInfor.accountName;
        if (dic[user_str] != undefined) {
          jQuery.each(dic, function (key, val) {
            if (val == '') {
              return;
            }
            if (key != undefined) {
              if (codeData == '') {
                codeData = val;
              } else {
                codeData = codeData = +',' + val;
              }
            }
          })
        } else {
          codeData = '';
        }
      } catch (e) {

      }
    }

    // codeData = '#XJDJHXNJN097,#XJDJHXNJN062,#XJDJHXNJN109,#XJDJHXNJN156,#XJDJHXNJN193,#XJDJHXNJN195,#XJDJHXNJN157,#XJDJHXNJN155,#XJDJHXNJN105,#XJDJHXNJN104,#XJDJHXNJN065,#XJDJHXNJN102,#XJDJHXNJN101,#XJDJHXNJN064,#SHJHXNJNMHSXFS37';
    if (codeData && codeData != '') {
      self.codeArray = [];
      self.nativeData = [];
      self.progress = 0;
      self.dialog = null;

      self.codeArray = codeData.split(',');
      self.nativeData = codeData.split(',');
      app.dialog.create({
        title: '请选择',
        text: '您有' + self.codeArray.length + '条任务待提交',
        buttons: [{
          text: '清除任务',
          onClick: function () { //清除数据
            native.saveDataByKey(userInfor.accountName, null);
            PollingCode = '';
          }
        },
        {
          text: '下次提交',
        },
        {
          text: '现在提交',
          onClick: function () { //提交
            self.progress = 0;
            self.dialog = app.dialog.progress('正在提交任务', self.progress);
            self.dialog.setText('任务数量 ' + 1 + ' / ' + self.codeArray.length);
            for (var i = 0; i < self.codeArray.length; i++) {
              Dao.submitPolling({
                userName: userInfor.accountName,
                deviceId: appKeyObj.deviceId,
                visualCode: self.codeArray[i],
                account: userInfor.accountName,
              }, function (data) {
                if (data.status == 200 || data.status == 202 || data.status == 203) {
                  self.progress += 1;
                  self.dialog.setProgress(self.progress);
                  self.dialog.setText('任务数量 ' + self.progress + ' / ' + self.codeArray.length);
                  if (self.progress == self.codeArray.length) {
                    self.dialog.close();
                  }
                  self.nativeData = common.deleteArrByEle(self.nativeData, data.data);
                  if (self.nativeData.length == 0) {
                    native.saveDataByKey(userInfor.accountName, null);
                  } else {
                    var codeStr = self.nativeData.join(',');
                    native.saveDataByKey(userInfor.accountName, codeStr);
                  }
                }
              });
            }
            PollingCode = '';
          }
        },
        ],
        verticalButtons: false,
      }).open();
    }
  }

  /**
   * explain:视频收藏
   * code:结果码
   * content：native.videoCollection('{"id":"1598","isConcem":0}')
   * @returns param {int code,String content}
   */
  _self.videoCollection = function (content) {
    //视频关注
    //视频tab
    var videoBean = JSON.parse(content);
    if (app.view.get("#monitor") && app.view.get("#monitor").router && app.view.get("#monitor").router.currentPageEl && app.view.get("#monitor").router.currentPageEl.f7Component) {
      var array = app.view.get("#monitor").router.currentPageEl.f7Component.moreUnitlist;
      array.forEach(function (v) {
        if (v.id == videoBean.id) {
          v.isConcem = videoBean.isConcem;
        }
      });
    } else {
      if (videoData[videoBean.id] != null) {
        videoData[videoBean.id].isConcem = videoBean.isConcem;
      }
    }
    //我的关注-视频
    if ($("#mineFocusOn_tabs_vedio").length > 0 && $("#mineFocusOn_tabs_vedio").hasClass("active")) {
      $("#mineFocusOn_tabs_vedio").click();
    }
    setTimeout(() => {
      app.view.get("#monitor").router.currentPageEl.f7Component.backToRefresh();
    }, 100);
  }

  /**
   * explain:定位结果
   * code:结果码
   * msg：分享结果信息
   * @returns param { int code,String msg}
   * double latitude ;获取纬度信息
   * double longitude ;获取经度信息
   * float radius ;获取定位精度，默认值为0.0f
   * String coorType ;获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
   * int errorCode ;获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
   * String addr ;获取详细地址信息
   * String country 获取国家
   * String province 获取省份
   * String city 获取城市
   * String district 获取区县
   * String street 获取街道信息
   */
  _self.locationResult = function (param) {
    try {
      var locationEntity = JSON.parse(param);
      //返回位置
      app.data.longitude = locationEntity.longitude;
      app.data.latitude = locationEntity.latitude;

      if (locationEntity.errorCode == "505") {
        app.getLoctext = "0";
        app.longitude = "0";
        app.latitude = "0";
        return;
      }

      if (jQuery(".index-tab.tab-active").length == 0) {
        app.getLoctext = "";
        app.longitude = "";
        app.latitude = "";
        app.getLoctext = locationEntity.addr
        app.latitude = locationEntity.latitude;
        app.longitude = locationEntity.longitude;
        $(".lefttext").val(locationEntity.addr);
      }

      let fn = app.view.current.el.f7View.router.currentPageEl.f7Component;
      if (fn.pageName == "home") {
        app.getLoctext = "";
        app.longitude = "";
        app.latitude = "";
        app.getLoctext = locationEntity.addr
        app.latitude = locationEntity.latitude;
        app.longitude = locationEntity.longitude;
      } else if (fn.pageName == "keyAlarm") {
        app.getLoctext = "";
        app.longitude = "";
        app.latitude = "";
        app.getLoctext = locationEntity.addr
        app.latitude = locationEntity.latitude;
        app.longitude = locationEntity.longitude;
        fn.getNativeBackLocation(app.longitude, app.latitude, app.getLoctext);
      } else if (fn.pageName == "signIn" || fn.pageName == "clockIn") {
        app.getLoctext = "";
        app.longitude = "";
        app.latitude = "";
        app.getLoctext = locationEntity.addr
        app.latitude = locationEntity.latitude;
        app.longitude = locationEntity.longitude;
        fn.getNativeBackLocation(app.longitude, app.latitude, app.getLoctext);
      } else if (fn.pageName == "oneAlarm") {
        app.getLoctext = "";
        app.longitude = "";
        app.latitude = "";
        app.getLoctext = locationEntity.addr
        app.latitude = locationEntity.latitude;
        app.longitude = locationEntity.longitude;
        fn.getNativeBackLocation(app.longitude, app.latitude, app.getLoctext);
      }

    } catch (e) {

    }
  }
  //格式化native触发js传递的jsonString
  _self.dealJson = function (jsonString, hasStatu) {
    if (jsonString && JSON.parse(jsonString)) {
      var obj = JSON.parse(jsonString);
      if (hasStatu && obj.status == 200) {
        return (obj.data);
      } else {
        return (obj);
      }
    } else {
      return ({});
    }
  }

  //捕获android实体返回键触发页面返回 myApp.getCurrentView().activePage.name
  _self.backButton = function () {
    if (native.getDataByKey("IS_OFFLINE_POPUP") != 1) { //当在开启离线维保的时候，出现弹窗禁止返回
      //图片浏览
      if (photoBrowser) {
        photoBrowser.close();
        photoBrowser = null;
        return;
      }
      //关闭所有弹窗
      if (jQuery('.popup.modal-in').length > 0 && !jQuery('.popup.modal-in').hasClass('login-popup')) {
        app.popup.close();
        return;
      }
      app.popover.close();
      //关闭图片
      if (linkPhotoBrowser) {
        linkPhotoBrowser.close();
      }
      //关闭找回密码
      if ($(".login-screen").css("display") == "block") {
        app.loginScreen.close();
        return;
      }
      //弹出层
      if ($(".layui-m-layercont").length > 0) {
        layer.closeAll();
        return;
      }
      //搜索框输入
      if (searchFlag == 1) {
        searchEl.parents(".navbar-inner").children().show();
        jQuery("#search-page-input").val('');
        jQuery('.search-btn').trigger("click");
        searchEl.parents(".navbar-inner").find(".nav-search-input-container").remove();
        searchFlag = 0;
        searchEl = [];
        return;
      }
      native.turnOffVoicePlay();
      //智慧海岛
      if (platformCode == "zhhd") {
        nativeService.backToHomePage();
        return;
      }

      if (app.view.current.history.length == 1 && !($('#soleKanban').length > 0 || jQuery(".back-to-moreKanban").is(":visible"))) {
        var secondTime = (new Date()).getTime();
        if (secondTime - firstTime > 2000) {
          app.methods.showToastCenter('再按一次退出程序');
          firstTime = secondTime;
        } else {
          nativeService.finishApp();
        }
      }

      // 离线作业直接返回
      if (app.view.current.el.f7View.router.currentRoute.route.name == 'offlineWork') {
        var secondTime = (new Date()).getTime();
        if (secondTime - firstTime > 2000) {
          app.methods.showToastCenter('再按一次退出程序');
          firstTime = secondTime;
        } else {
          nativeService.finishApp();
        }
        return;
      }

      if (app.view.current.el.f7View.router.currentPageEl.f7Component.pageName == 'examPage') {
        app.view.current.el.f7View.router.currentPageEl.f7Component.commonHtml()
        return
      }
      if (app.view.current.el.f7View.router.currentPageEl.f7Component.pageName == 'examResult') {
        app.view.current.el.f7View.router.currentPageEl.f7Component.goIndex()
        return
      }
      let routeName = app.view.current.el.f7View.router.currentRoute.route.name
      if (routeName == 'checkApply' || routeName == 'addDevice') {
        let myVue = document.getElementById('vueIframe').contentWindow.myVue
        if (myVue) {
          if (myVue.$route.name == 'InspectDetail' && myVue.$route.query.tabId === '3') {
            return app.methods.backToTab()
          }
          if (myVue.$route.name != 'InspectMain' && myVue.$route.name != 'AddDevice') {
            return myVue.$router.go(-1)
          }
          if (myVue.$route.name == 'AddDevice' && myVue.showScanTip) {
            return myVue.showScanTip()
          }
          if (myVue.$route.name == 'DeviceForm' && myVue.showChooseVideo) {
            return myVue.showChooseVideo()
          }
        }
      }
      app.methods.backToTab();
      // if (app.view.current.history.length == 1) {
      //     //多单位>右上角选择单位>单单位 返回
      //     if ($('#soleKanban').length > 0 || jQuery(".back-to-moreKanban").is(":visible")){
      //         app.view.get("#home").router.currentPageEl.f7Component.backToAllPlat();
      //     }else{
      //         var secondTime = (new Date()).getTime();
      //         if (secondTime - firstTime > 2000){
      //             app.methods.showToastCenter('再按一次退出程序');
      //             firstTime = secondTime;
      //         } else {
      //             nativeService.finishApp();
      //         }
      //     }
      // } else if (app.view.current.history.length == 2) {
      //     app.methods.backToTab();
      // } else if (app.view.current.history.length == 3){
      //     //多单位>单位实时安全指数>单单位 返回
      //     if (app.view.current.history[2].indexOf("/soleKanbanFromUnitSafety/") > -1
      //         && app.view.current.history[1].indexOf("/unitSafetyExponentMore/") > -1
      //     ) {//清空全局orgId
      //         single_Orgid = "";
      //         single_OrgName = "";
      //     }
      //     app.methods.backToTab();
      //     // app.router.back();
      // }else{
      //     app.methods.backToTab();
      //     // app.router.back();
      // }
    }
  }

  //退出登录
  _self.logOut = function () {
    userInfor = "";
    userLoggedIn = false;
    _self.setUserInfor("");
    _self.saveDataByKey('loginStatus', 'no'); //保存登录状态 登录成功yes 退出登录no
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.logOut();
      } catch (e) { }
    } else if (isIOS) {
      try {
        PollingCode = '';
        loginStatus = undefined;
        window.webkit.messageHandlers.logOut.postMessage("");
        if (native.getDataByKey('username') != undefined) {
          jQuery("#login-form input[name='accout']")[0].value = native.getDataByKey('username');
        }
        if (native.getDataByKey('password') != undefined) {
          jQuery("#login-form input[name='password']")[0].value = native.getDataByKey('password');
        }
      } catch (e) { }
    } else {
      location.reload();
    }
  }

  _self.checkVersion = function () {
    var u = navigator.userAgent;
    //网页登录不提示更新
    // weixin
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return;
    }
    //web
    if ("Win32" === navigator.platform.toString() || "MacIntel" === navigator.platform.toString()) {
      return;
    }
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    var type = isAndroid ? 2 : (isIOS ? 1 : 0);
    Dao.findOrgByOrgCode({
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
      orgCode: platformCode || app.data.defaultPlatCode
    }, function (re) {
      Dao.checkVersion({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
        organizationId: re,
        type: type,
        isCustom: 1,
      }, function (data) {
        if (data) {
          var versionCode = native.getVersion();
          if (isIOS) {
            versionCode = IOSVersion;
          }
          var buttons = [];
          if (1 === data.isManupdate) {
            buttons = [{
              text: '现在更新',
              onClick: function () {
                // app.methods.showToastBottom('现在更新');
                native.downloadByBrowser((ZHXF_IS_AIO ? location.origin : '') + data.url);
              },
              close: false
            }]
          } else {
            buttons = [{
              text: '现在更新',
              onClick: function () {
                // app.methods.showToastBottom('现在更新');
                native.downloadByBrowser((ZHXF_IS_AIO ? location.origin : '') + data.url);
              },
            },
            {
              text: '以后更新',
            },
            ]
          }
          if (versionCode < data.softNumber) {
            app.dialog.create({
              title: '发现新版本:V' + data.softName,
              text: data.content,
              buttons: buttons,
              verticalButtons: true,
            }).open();
          }
        }
      });
    }, null, function (res) { });
  }

  //关闭更新窗口 加载loading
  _self.notifyH5loading = function () {
    app.dialog.close();
    common.loading(1);
  }

  // 重新加载页面
  _self.reloadH5FromFile = function () {
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS

    } else if (/(Android)/i.test(navigator.userAgent)) { //判断Android
      try {
        nativeService.reloadH5FromFile();
      } catch (e) {

      }
    } else { //pc
      location.reload();
    };
  }

  /**
   * 提交离线数据
   * @param callback
   */
  _self.checkOfflineCommitData = function (callback) {
    if (!navigator.onLine) {
      callback(1, "请确保当前网络正常！");
      return;
    }

    app.request({
      url: contextPath + 'ilink-app-h5-zd/json/offlineCheck.json',
      dataType: "json",
      contentType: "application/json",
      method: 'get',
      timeout: 3000,
      success: function () {
        let commitData = native.getDataByKey("offlineData-work-commit-data");
        if (!commitData) {
          callback(2, "未发现需要提交的作业数据！");
          native.saveDataByKey("IS_OFFLINE_MODULE", 0);
          native.saveDataByKey("OFFLINE_SELECT_FLAG", 0)
          native.saveDataByKey("IS_OFFLINE_POPUP", 0);
          native.reloadH5FromFile();

          return;
        }

        let localDataJSON = JSON.parse(commitData);
        if (localDataJSON.length == 0) {
          callback(2, "未发现需要提交的作业数据！");
          native.saveDataByKey("IS_OFFLINE_MODULE", 0);
          native.saveDataByKey("OFFLINE_SELECT_FLAG", 0)
          native.saveDataByKey("IS_OFFLINE_POPUP", 0);
          native.reloadH5FromFile();
        }
        START_OFFLINE_COMMITDATA = true;
        _self.off_errorData = [];
        _self.off_successCount = 0;
        _self.off_submitCount = 0;

        let commitDataJSON = localDataJSON.filter(n => {
          return n.api != 'app/examine/commitPointResult'
        })
        // 点位巡检结果聚合
        let inspectParamList = localDataJSON.filter(n => {
          return n.api == 'app/examine/commitPointResult'
        }).map(n => {
          return JSON.parse(n.param)
        })
        // 批量提交巡检结果
        commitDataJSON.push({
          api: 'app/examine/commitPointResult',
          param: JSON.stringify({
            dataListStr: JSON.stringify(inspectParamList)
          }),
          requestType: "post",
          userName: userInfor.accountName
        })

        callback(0, "开始提交", commitDataJSON.length, 0, 0);
        let len = commitDataJSON.length
        for (let i = 0; i < len; i++) {
          _self.uploadEachTask(commitDataJSON[i], len, callback)
        }
      },
      error: function () {
        callback(1, "请确保已连接正确的网络！");
      }
    })
  }

  _self.uploadEachTask = function (idata, dataLength, callback) {
    if (idata.userName == userInfor.accountName) {
      common.multiUpload(idata.param, function (param) {
        Dao.requestData(idata.api, JSON.parse(param),
          function (data, info, status) {
            _self.off_submitCount++
            if (status == 200) {
              _self.off_successCount++;
              callback(0, "提交成功", dataLength, _self.off_successCount, _self.off_errorData.length);
              if (_self.off_submitCount >= dataLength) {
                if (_self.off_errorData.length == 0) {
                  // 提交完成，全部成功，关闭离线模式
                  native.saveDataByKey("IS_OFFLINE_MODULE", 0);
                  // 关闭离线数据提交模式
                  START_OFFLINE_COMMITDATA = false;
                  // _self.saveDataByKey("offlineData-work-commit-data", JSON.stringify(_self.off_errorData));
                  _self.saveDataByKey("offlineData-work-commit-data", "[]");
                }
              }
            } else {
              _self.off_errorData.push(idata);
              callback(0, "提交失败", dataLength, _self.off_successCount, _self.off_errorData.length);
              if (_self.off_submitCount == (dataLength - 1)) {
                _self.saveDataByKey("offlineData-work-commit-data", JSON.stringify(_self.off_errorData));
              }
            }

          },
          function (e) {
            _self.off_submitCount++
            _self.off_errorData.push(idata);
            callback(0, "提交失败", dataLength, _self.off_successCount, _self.off_errorData.length);
            if (_self.off_submitCount == (dataLength - 1)) {
              _self.saveDataByKey("offlineData-work-commit-data", JSON.stringify(_self.off_errorData));
            }
          },
          idata.requestType, false);
      })
    }
  }

  _self.checkH5Version = function () {
    Dao.checkVersion({
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
      organizationId: 0,
      type: 5,
      isCustom: 0,
    }, function (data) {
      if (data) {
        if (data.softNumber > (CONFIGBOX[CONFIGKEY].version || 0)) {
          native.clear_cache();
          console.log("数据更新中,大约需要消耗" + data.size + "M数据流量。");
          try {
            if (/(Android)/i.test(navigator.userAgent)) {
              nativeService.updateH5Data((ZHXF_IS_AIO ? location.origin : '') + data.url, data.softNumber);
            }
          } catch (e) {

          }
        }
      }
    });
  }
  // 针对X的底部适配
  // _self.sureIosDevice = function() {
  //     var u = navigator.userAgent;
  //     var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
  //     if (isIOS) {
  //         var deviceWidth = window.screen.width;
  //         var deviceHeight = window.screen.height;
  //         if (deviceWidth == 375 & deviceHeight == 812 || deviceWidth == 896 & deviceHeight == 414) {
  //             jQuery("#bottom_nav").addClass("bottom_nav_ios");
  //         } else {
  //             jQuery("#bottom_nav").removeClass("bottom_nav_ios");
  //         }

  //     }
  // }

  /**
   * @Author: Chili
   * @Description: 大屏里面的打电话功能
   * @Date: 2019-07-23 14:08:02
   */
  _self.openBsVedioCall = function (jsonData) {
    var transString = JSON.stringify(jsonData);
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isIOS = u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1; //IOS终端
    if (isAndroid) {
      try {
        nativeService.openRongCallVideoPage(transString);
      } catch (e) {

      }
    } else if (isIOS) {
      try {
        window.webkit.messageHandlers.openCall.postMessage(jsonData);
      } catch (e) {

      }
    }
  }

  //进入前台后台 0:回到app 1:进入后台 2:杀死app
  _self.backGround = function (flag) {
    uploadUserTime(flag);
    var pageEl = app.view.current.el.f7View.router.currentPageEl.f7Component;
    if ((pageEl && pageEl.pageName == "studyDetail")) {
      app.view.current.el.f7View.router.currentPageEl.f7Component.stopOrStartCalcTime(flag);
    }
  }
  return _self;
})(window.native || {});